define(function( require ) {
    var Marionette = require('marionette'),
        ItemView = require('components/image/1.0.0/views/image_upload_item');

    require('jqueryui');

    var tpl = require('text!components/image/1.0.0/templates/image_upload.html');
    return Marionette.CompositeView.extend({
        tagName: 'form',
        className: 'form-horizontal',
        template: _.template(tpl),
        itemView: ItemView,
        itemViewContainer: '.js-upload-image-list',
        events: {
            'change .js-fileupload-input': 'selectFile'
        },
        initialize: function() {
            this.listenTo(window.NC, 'image:upload', this.upload);
        },
        // You might need to override this if you've overridden appendHtml
        appendBuffer: function(collectionView, buffer) {
            collectionView.$('.fileinput-button').before(buffer);
        },

        // Append the HTML to the collection's `el`.
        // Override this method to do something other
        // then `.append`.
        appendHtml: function(collectionView, itemView, index){
            if (collectionView.isBuffering) {
                // buffering happens on reset events and initial renders
                // in order to reduce the number of inserts into the
                // document, which are expensive.
                collectionView.elBuffer.appendChild(itemView.el);
                collectionView._bufferedChildren.push(itemView);
            }
            else {
                // If we've already rendered the main collection, just
                // append the new items directly into the element.
                collectionView.$('.fileinput-button').before(itemView.el);
            }
        },
        selectFile: function(e) {
            var files = e.target.files;

            var that = this;
            _.each(files, function(file) {
                var kb = file.size / 1024 ;
                if (kb > that.collection.maxSize) {
                    return;
                }
                if (file.name.match(/(\.|\/)(gif|jpe?g|png)$/i)) {
                    that.previewAndAdd(file);
                }
            });
            $(e.target).val('');
        },
        previewAndAdd: function(file) {
            var fileReader = new FileReader();

            var that = this;
            fileReader.onload = function(e) {
                that.collection.add({
                    src: e.target.result,
                    file: file
                });
                window.NC.trigger('image:number:change');
            }

            fileReader.readAsDataURL(file);
        },
        upload: function(e) {
            this.collection.sync({
                success: function() {
                    this.render();
                }.bind(this)
            });
        },
        onRender: function() {
            var view = this;

            this.$('.js-upload-image-list').sortable({
                items: '> .sort',
                cursor: 'move',
                start: function(event, ui) {
                    ui.item.data('startPos', ui.item.index());
                },
                stop: function(event, ui) {
                    var startPos = ui.item.data('startPos');
                    var endPos = ui.item.index();

                    if (startPos === endPos) {
                        return;
                    }
                    view.collection.swapImages(startPos, endPos);
                }
            });
            return this;
        }

    });
});
